<?php

Class DB {

    private $last_query;
    private $last_inserted_id;
    private $affected_rows;

    public function __construct($host, $user, $password, $db) {
        if (mysql_connect($host, $user, $password)) {
            if (!mysql_select_db($db)) {
                die("Problema al conectar a la Base de Datos.");
            }
            mysql_query("SET NAMES 'utf8'");
        } else {
            die("Problema al conectar al Servidor MySql");
        }
    }

    public function insert($table, $data) {
        foreach ($data as $key => $val) {
            $fields[] = $key;
            $values[] = $this->escape($val);
        }
        $this->last_query = "INSERT INTO " . $table . " (" . implode(', ', $fields) . ") VALUES (" . implode(', ', $values) . ")";
        if (mysql_query($this->last_query)) {
            $this->last_inserted_id = mysql_insert_id();
            return true;
        }
        return false;
    }

    public function delete($table, $cond) {
        foreach ($cond as $key => $val) {
            $fields[] = $key;
            $values[] = Bd::escape($val);
        }
        $this->last_query = "delete from $table Where $fields[0] = $values[0]";
        if (mysql_query($this->last_query)) {
            return true;
        } else {
            return false;
        }
    }

    private function escape($str) {
        if ($str == null) {
            $str = 'NULL';
        } else if (is_string($str)) {
            $str = "'" . mysql_real_escape_string($str) . "'";
        } elseif (is_bool($str)) {
            $str = ($str === FALSE) ? 0 : 1;
        }
        return $str;
    }

    public function update($table, $values, $where) {
        foreach ($values as $key => $val) {
            $valstr[] = $key . ' = ' . Bd::escape($val);
        }
        $this->last_query = "UPDATE " . $table . " SET " . implode(', ', $valstr);
        $this->last_query .= ( $where != '' AND count($where) >= 1) ? " WHERE " . $where : '';
        if (mysql_query($this->last_query)) {
            return true;
        }
        return false;
    }

    public function getLastInsertedId() {
        return $this->last_inserted_id;
    }

    public function getLastQuery() {
        return $this->last_query;
    }

    public function affectedRows() {
        return $this->affected_rows;
    }

    /**
     *
     * @param type $sql Consulta SQL a ejecutar
     * @return array cargado con los datos cargados de la ejecucion de la consulta
     */
    public function query($sql) {
        $this->last_query = $sql;
        $result = mysql_query($this->last_query);
        if (mysql_num_rows($result) == 0) {
            return null;
        } else {
            while ($row = mysql_fetch_assoc($result)) {
                $data[] = $row;
            }
            return $data;
        }
    }

}